'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 新手引导
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var roleModel = require('../../../models/roleModel');
var guideModel = require('../../../models/guideModel');
var guideAtkData = require('../../../libs/war/guideAtkData');
var guideDefData = require('../../../libs/war/guideDefData');
var dataApi = require('../../../libs/dataApi');
var PlayerManager = require('../../../libs/playerManager');
var rewardService = require('../../../services/rewardService');
var _ = require('lodash');
var constantUtil = require('../../../util/constantUtil.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 设置新手引导的进度
 */
Handler.prototype.start = function (msg, session, next) {
    var role_id = session.uid;
    var progress = msg.progress;

    if (!progress) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['bag', 'role', 'build', 'soldier', 'guide', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var guide_model = player_manager.guide;
                var role_model = player_manager.role;
                var start_progress = guide_model.getStartProgress();
                if (start_progress >= progress) {
                    return next(null, {
                        code: Code.OK
                    });
                }

                guide_model.setStartProgress(progress);

                // 发奖励
                var reward_list_all = dataApi.guide_reward.findById(progress);
                var reward_list = [];
                _.each(reward_list_all, function (guide_reward) {
                    if (guide_reward.job_type === role_model.job_type) {
                        reward_list.push(guide_reward);
                    }
                });
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_OTHER, operationType.OPR_OTHER_GUIDE_REWARD);
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            player_manager.save();
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 设置新手引导的进度
 */
Handler.prototype.end = function (msg, session, next) {
    var role_id = session.uid;
    var progress = msg.progress;

    if (!progress) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var guide_model;
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'bag', 'vip', 'build', 'task', 'daily_task', 'achieve', 'tech', 'guide', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                guide_model = player_manager.guide;
                var role_model = player_manager.role;
                guide_model.setProgress(progress);

                // 标识新手
                if (guide_model.getProgress() >= constantUtil.value('newplayer_protect_step')) {
                    role_model.setRecruits();
                }
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    progress: guide_model.getProgress()
                }
            });
        }
    );
};

Handler.prototype.war = function (msg, session, next) {
    var role_id = session.uid;

    var role_model;
    var atk_data;
    var def_data;
    async.waterfall([
            function (cb) {
                roleModel.getByRoleId(role_id, cb);
            },
            function (model, cb) {
                role_model = model;

                atk_data = guideAtkData.getData(role_model.getJob());
                def_data = guideDefData.getData();

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    record_id: 0,
                    war_time: 9999999,
                    atk: atk_data,
                    def: def_data
                }
            });
        }
    );
};

/**
 * 保存进度信息列表
 */
Handler.prototype.save = function (msg, session, next) {
    var role_id = session.uid;
    var guide = msg.guide;
    var guide_model;

    if (!guide) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['bag', 'role', 'build', 'guide', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
                    cb
                );
            },

            function (cb) {
                guide_model = player_manager.guide;
                var role_model = player_manager.role;

                if (!guide_model.addGuideList(guide)) {
                    return next(null, {
                        code: Code.GUIDE_LIST_THERE
                    });
                } else {

                    // 增加记录
                    guide_model.addGuideList(guide);
                }
                player_manager.save();
                cb();
            },
            function (cb) {

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 发放奖励
 */
Handler.prototype.give = function (msg, session, next) {
    var role_id = session.uid;
    var guide_id = msg.guide_id;

    if (!guide_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['bag', 'role', 'build', 'soldier', 'guide', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
                    cb
                );
            },

            function (cb) {
                var guide_model = player_manager.guide;
                var role_model = player_manager.role;

                if (guide_model.getGuideId(guide_id) !== 0) {
                    return next(null, {
                        code: Code.HAS_RUECEIVED_REWARD
                    });
                } else {

                    // 记录领取新手引导奖励是领取状: 1
                    guide_model.addGuideId(guide_id);

                    // 发放奖励
                    var reward_list_all = dataApi.guide_reward.findById(guide_id);

                    var reward_list = [];
                    _.each(reward_list_all, function (guide_reward) {
                        if (guide_reward.job_type === role_model.job_type) {
                            reward_list.push(guide_reward);
                        }
                    });

                    rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_OTHER, operationType.OPR_OTHER_GUIDE_REWARD);
                }
                player_manager.save(cb);
            },
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 强制奖励发放接口
 */

Handler.prototype.forcedGive = function (msg, session, next) {
    var role_id = session.uid;
    var progress = msg.progress;

    if (!progress) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var reward_list = [];

    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['bag', 'role', 'build', 'soldier', 'guide', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var guide_model = player_manager.guide;
                var role_model = player_manager.role;
                var start_progress = guide_model.getStartProgress();
                if (start_progress >= progress) {
                    return next(null, {
                        code: Code.OK
                    });
                }

                // 是否领取过
                if (guide_model.getGuideId(progress * 1000) !== 0) {
                    return next(null, {
                        code: Code.HAS_RUECEIVED_REWARD
                    });
                } else {

                    // 记录领取新手引导奖励是领取状: 1
                    guide_model.addGuideId(progress * 1000);

                    // 发奖励
                    var reward_list_all = dataApi.trigger_guide_reward.findById(progress);

                    _.each(reward_list_all, function (guide_reward) {
                        if (guide_reward.job_type === role_model.job_type) {
                            reward_list.push(guide_reward);
                        }
                    });

                    rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_OTHER, operationType.OPR_OTHER_GUIDE_REWARD);
                }

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};
